
wifi.setmode(wifi.STATIONAP)
wifi.ap.config({ssid="MyPersonalSSID", auth=wifi.OPEN})
enduser_setup.manual(true)
enduser_setup.start(
  function()
    print("Connected to WiFi as:" .. wifi.sta.getip())
  end,
  function(err, str)
    print("enduser_setup: Err #" .. err .. ": " .. str)
  end
)

counter=0
mac=""
Version=0
timer = tmr.create()

function readfile()
    --set Version number
    Version = 0
    if file.open("version.txt") then
        Version = file.readline()
        Version = tonumber(Version)
        print("old version is:"..Version)
        print("read version.txt success")
    else
        print("not found version.txt")
    end
end


function Reconn()
    if wifi.sta.getip() == nil then
        print("waiting...")
    else
        timer:stop()
        print("ip is: "..wifi.sta.getip())

        --change your ip address here
        http.get('https://gitee.com/Zero0a/hs-greenwater-switcher/raw/master/nodemcu/version.txt',nil,
            function(code, data)
                if code < 0 then
                    print("http error")
                else
                    print("http ok")
                    print(data)
                    data = tonumber(data)
                    
                    if data > Version then              --如果读取回来的版本号大于本地的
                        print(data)
                        file.open("version.txt",'w+')   --打开version.txt
                        file.writeline(data)            --清空version.txt并替换里面版本号
                        file.close()                    --关闭文件

                        --change your ip address here
                        http.get('https://gitee.com/Zero0a/hs-greenwater-switcher/raw/master/nodemcu/run.lua',nil,
                            function(codes, datas)
                                if codes < 0 then
                                    print("http error")
                                    node.restart()
                                else
                                    file.open("run.lua",'w+')   --打开本地led.lua
                                    file.writeline(datas)       --清空并写入新代码
                                    file.close()                --关闭文件
                                    node.restart()
--dofile("run.lua")           --执行led.lua
                                end
                            end)
                            
                    else                                --若版本号无更新则继续执行以前的代码文件
                        print("not new version")        
                        dofile("run.lua")               --继续执行 led.lua
                    end
                end
            end)
        
    end
end

readfile()
timer:alarm(5000, tmr.ALARM_AUTO, Reconn)

